const app = getApp();
const icons = require('../../utils/icons.js');

Page({
  data: {
    icons: icons,
    tabs: [
      { name: '待接单', count: 0 },
      { name: '待拿货', count: 0 },
      { name: '待收货', count: 0 }
    ],
    currentTab: 0,
    orders: {
      0: [],
      1: [],
      2: []
    },
    orderList: [],
    todayStats: {
      todayIncome: '0.00',    // 今日收入
      completedOrders: 0,     // 完成订单数
      onlineHours: '0.0'      // 在线时长（保留原有显示）
    },
    refreshTimer: null,       // 定时器
    isLoggedIn: false         // 登录状态
  },

  onLoad() {
    const savedTab = wx.getStorageSync('currentTab') || 0;
    this.setData({ currentTab: savedTab });

    // 检查登录状态
    this.checkLoginStatus();

    // 只在 onLoad 里初始化数据
    if (this.data.isLoggedIn) {
      this.loadAllOrders(savedTab);
      this.fetchTodayStats();
    }
  },

  onShow() {
    // 检查登录状态
    this.checkLoginStatus();

    // 切回页面时只刷新当前 tab 的数据（不影响 tab 状态）
    if (this.data.isLoggedIn) {
      const tab = this.data.currentTab;
      this.loadOrdersForTab(tab);
      this.fetchTodayStats();
      this.startAutoRefresh(); // 开始自动刷新
    }
  },

  onHide() {
    this.stopAutoRefresh(); // 页面隐藏时停止自动刷新
  },

  onUnload() {
    this.stopAutoRefresh(); // 页面卸载时停止自动刷新
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    const isLoggedIn = !!(token && riderId);
    this.setData({ isLoggedIn });

    if (!isLoggedIn) {
      // 未登录时清空订单数据
      this.setData({
        orders: { 0: [], 1: [], 2: [] },
        orderList: [],
        todayStats: {
          todayIncome: '0.00',
          completedOrders: 0,
          onlineHours: '0.0'
        }
      });
      this.updateCounts();
    }
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({
      url: '/pages/logs/logs'
    });
  },

  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    if (index === this.data.currentTab) return;

    this.setData({ currentTab: index });
    wx.setStorageSync('currentTab', index);
    this.updateOrderList(index);

    // 切换 tab 后只加载当前 tab 的数据
    this.loadOrdersForTab(index);
  },

  loadAllOrders(savedTab) {
    this.fetch0();
    this.fetch1();
    this.fetch2();
    this.updateOrderList(savedTab);
  },

  loadOrdersForTab(index) {
    if (index === 0) this.fetch0();
    if (index === 1) this.fetch1();
    if (index === 2) this.fetch2();
  },

  fetch0() {
    const token = app.globalData.ridertoken;
    const ip = app.globalData.userIPInfo;

    if (!token) {
      this.setData({ ['orders.0']: [] });
      return;
    }

    wx.request({
      url: `${ip}/api/orders/listNoOrdersReceived`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: res => {
        const rawOrders = res.data?.data || [];
        const filteredOrders = rawOrders.filter(item => item.orderStatusName === '待接单');
  
        const orders0 = filteredOrders.map(item => {
          const [pickupLat = 0, pickupLng = 0] = (item.merchantlatAndLng || '').split(',').map(Number);
          const [deliveryLat = 0, deliveryLng = 0] = (item.userlatAndLng || '').split(',').map(Number);
  
          return {
            id: item.id?.toString() || '',
            title: item.merchantName || '未知商家',
            userId: item.userId,
            pickup: {
              latitude: pickupLat,
              longitude: pickupLng,
              address: item.merchantTotalAddress || item.addressDetail || `${item.province || ''} ${item.city || ''} ${item.district || ''}`.trim()
            },
            delivery: {
              latitude: deliveryLat,
              longitude: deliveryLng,
              address: item.addressDetail || `${item.province || ''} ${item.city || ''} ${item.district || ''}`.trim()
            },
            distance: 0,
            eta: '',
            income: item.paidAmount || 0,
            statusText: item.orderStatusName || '',
            orderSn: item.orderSn || '',
            goodsInfoList: Array.isArray(item.goodsInfoList) ? item.goodsInfoList.map(goods => ({
              name: goods.name || '',
              count: goods.count || 0,
              skuName: goods.sku?.name || '',
              relatedOrders: goods.relatedOrders || []
            })) : []
          };
        });
  
        this.setData({ ['orders.0']: orders0 });
        this.updateCounts();
        this.updateOrderList(0);
        // 计算距离和预计时间
        this.calculateDistanceAndETA(0);
      },
      fail: () => {
        wx.showToast({ title: '请求接口失败', icon: 'none' });
        this.setData({ ['orders.0']: [] });
      }
    });
  },
  
  fetch1() {
    const token = app.globalData.ridertoken;
    const ip = app.globalData.userIPInfo;

    if (!token) {
      this.setData({ ['orders.1']: [] });
      return;
    }

    wx.request({
      url: `${ip}/api/orders/rider/list?riderId=1&orderStatus=3`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: res => {
        const rawOrders = res.data?.data || [];
  
        const orders1 = rawOrders.map(item => {
          const [pickupLat = 0, pickupLng = 0] = (item.merchantlatAndLng || '').split(',').map(Number);
          const [deliveryLat = 0, deliveryLng = 0] = (item.userlatAndLng || '').split(',').map(Number);
  
          return {
            id: item.id?.toString() || '',
            title: item.merchantName || '未知商家',
            userId: item.userId,
            pickup: {
              latitude: pickupLat,
              longitude: pickupLng,
              address: item.merchantTotalAddress || item.addressDetail || `${item.province || ''} ${item.city || ''} ${item.district || ''}`.trim()
            },
            delivery: {
              latitude: deliveryLat,
              longitude: deliveryLng,
              address: item.addressDetail || `${item.province || ''} ${item.city || ''} ${item.district || ''}`.trim()
            },
            distance: 0,
            eta: '',
            income: item.paidAmount || 0,
            statusText: item.orderStatusName || '',
            orderSn: item.orderSn || '',
            goodsInfoList: item.goodsInfoList || []
          };
        });
  
        this.setData({ ['orders.1']: orders1 });
        this.updateCounts();
        this.updateOrderList(1);
        // 计算距离和预计时间
        this.calculateDistanceAndETA(1);
      },
      fail: () => {
        wx.showToast({ title: '请求接口失败', icon: 'none' });
        this.setData({ ['orders.1']: [] });
      }
    });
  },
  
  fetch2() {
    const token = app.globalData.ridertoken;
    const ip = app.globalData.userIPInfo;

    if (!token) {
      this.setData({ ['orders.2']: [] });
      return;
    }

    wx.request({
      url: `${ip}/api/orders/rider/list?riderId=1&orderStatus=4`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: res => {
        const rawOrders = res.data?.data || [];
  
        const orders2 = rawOrders.map(item => {
          const [pickupLat = 0, pickupLng = 0] = (item.merchantlatAndLng || '').split(',').map(Number);
          const [deliveryLat = 0, deliveryLng = 0] = (item.userlatAndLng || '').split(',').map(Number);
  
          return {
            id: item.id?.toString() || '',
            title: item.merchantName || '未知商家',
            userId: item.userId,
            pickup: {
              latitude: pickupLat,
              longitude: pickupLng,
              address: item.merchantTotalAddress || item.addressDetail || `${item.province || ''} ${item.city || ''} ${item.district || ''}`.trim()
            },
            delivery: {
              latitude: deliveryLat,
              longitude: deliveryLng,
              address: item.addressDetail || `${item.province || ''} ${item.city || ''} ${item.district || ''}`.trim()
            },
            distance: 0,
            eta: '',
            income: item.paidAmount || 0,
            statusText: item.orderStatusName || '',
            orderSn: item.orderSn || '',
            goodsInfoList: item.goodsInfoList || []
          };
        });
  
        this.setData({ ['orders.2']: orders2 });
        this.updateCounts();
        this.updateOrderList(2);
        // 计算距离和预计时间
        this.calculateDistanceAndETA(2);
      },
      fail: () => {
        wx.showToast({ title: '请求接口失败', icon: 'none' });
        this.setData({ ['orders.2']: [] });
      }
    });
  },

  // 开始自动刷新
  startAutoRefresh() {
    // 清除之前的定时器
    this.stopAutoRefresh();

    // 设置5秒刷新一次
    this.setData({
      refreshTimer: setInterval(() => {
        this.fetchTodayStats();
      }, 5000)
    });
  },

  // 停止自动刷新
  stopAutoRefresh() {
    if (this.data.refreshTimer) {
      clearInterval(this.data.refreshTimer);
      this.setData({
        refreshTimer: null
      });
    }
  },

  // 获取今日统计数据
  fetchTodayStats() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    if (!token || !riderId) {
      return; // 未登录时不获取统计数据
    }

    // 获取今日已完成订单 (orderStatus=5表示已完成)
    wx.request({
      url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=5`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        if (res.data.code === 200) {
          const allCompletedOrders = res.data.data || [];

          // 筛选今日完成的订单
          const today = new Date();
          const todayStr = today.toISOString().split('T')[0]; // YYYY-MM-DD格式

          const todayOrders = allCompletedOrders.filter(order => {
            if (!order.updateTime) return false;
            const orderDate = new Date(order.updateTime).toISOString().split('T')[0];
            return orderDate === todayStr;
          });

          // 计算今日收入
          const todayIncome = todayOrders.reduce((sum, order) => {
            return sum + (parseFloat(order.deliveryFee) || 0);
          }, 0);

          // 完成订单数
          const completedOrders = todayOrders.length;

          // 计算在线时长（简化计算，实际应该从后端获取）
          const onlineHours = this.calculateOnlineHours(todayOrders);

          this.setData({
            todayStats: {
              todayIncome: todayIncome.toFixed(2),
              completedOrders: completedOrders,
              onlineHours: onlineHours
            }
          });
        }
      },
      fail: () => {
        // 静默处理错误
      }
    });
  },

  // 计算在线时长（简化算法）
  calculateOnlineHours(orders) {
    if (orders.length === 0) return '0.0';

    // 简化计算：假设每单平均30分钟
    const avgTimePerOrder = 0.5; // 0.5小时
    const totalHours = orders.length * avgTimePerOrder;

    return Math.min(totalHours, 12).toFixed(1); // 最多显示12小时
  },

  updateCounts() {
    const newTabs = this.data.tabs.map((tab, index) => {
      return {
        name: tab.name,
        count: (this.data.orders[index] || []).length
      };
    });
    this.setData({ tabs: newTabs });
  },

  updateOrderList(tabIndex) {
    this.setData({
      orderList: this.data.orders[tabIndex] || []
    });
  },

  // 获取并存储当前位置
  getCurrentLocation(callback) {
    // 先检查本地存储是否有位置信息（1小时内有效）
    const storedLocation = wx.getStorageSync('riderLocation');
    if (storedLocation && storedLocation.timestamp) {
      const now = Date.now();
      const oneHour = 60 * 60 * 1000; // 1小时
      if (now - storedLocation.timestamp < oneHour) {
        if (callback) callback(storedLocation);
        return;
      }
    }

    // 先检查授权状态
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation']) {
          // 已授权，直接获取位置
          this.getLocationDirect(callback);
        } else {
          // 未授权，请求授权
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              this.getLocationDirect(callback);
            },
            fail: () => {
              wx.showModal({
                title: '位置权限',
                content: '需要获取您的位置信息来计算配送距离，请在设置中开启位置权限',
                showCancel: false,
                confirmText: '知道了'
              });
              if (callback) callback(null);
            }
          });
        }
      },
      fail: () => {
        if (callback) callback(null);
      }
    });
  },

  // 直接获取位置
  getLocationDirect(callback) {
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success: (res) => {
        const location = {
          latitude: res.latitude,
          longitude: res.longitude,
          timestamp: Date.now()
        };

        // 存储到本地
        wx.setStorageSync('riderLocation', location);

        if (callback) callback(location);
      },
      fail: (error) => {

        // 根据错误类型给出不同提示
        let errorMsg = '获取位置失败';
        if (error.errMsg.includes('auth deny')) {
          errorMsg = '位置权限被拒绝';
        } else if (error.errMsg.includes('timeout')) {
          errorMsg = '获取位置超时';
        } else if (error.errMsg.includes('system deny')) {
          errorMsg = '系统拒绝位置访问';
        }

        wx.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        });

        if (callback) callback(null);
      }
    });
  },

  // 计算距离和预计时间
  calculateDistanceAndETA(tabIndex) {
    const orders = this.data.orders[tabIndex] || [];
    const key = app.globalData.locationKey;

    if (!key || orders.length === 0) return;

    // 为每个订单计算距离
    orders.forEach((order, index) => {
      this.calculateSingleDistance(order, tabIndex, index);
    });
  },

  // 计算单个订单的距离
  calculateSingleDistance(order, tabIndex, orderIndex) {
    const key = app.globalData.locationKey;

    // 根据标签页决定计算方式
    if (tabIndex === 1) {
      // 待拿货：计算从当前位置到商家的距离
      this.calculateRiderToMerchant(order, tabIndex, orderIndex);
    } else if (tabIndex === 2) {
      // 待收货：计算从当前位置到用户的距离
      this.calculateRiderToUser(order, tabIndex, orderIndex);
    } else {
      // 待接单：计算商家到用户的距离
      this.calculateMerchantToUser(order, tabIndex, orderIndex);
    }
  },

  // 计算骑手到商家的距离（待拿货）
  calculateRiderToMerchant(order, tabIndex, orderIndex) {
    this.getCurrentLocation((riderLocation) => {
      if (!riderLocation || !order.pickup.latitude || !order.pickup.longitude) {
        this.updateOrderDistance(tabIndex, orderIndex, '位置获取失败', '位置获取失败');
        return;
      }

      const from = `${riderLocation.latitude},${riderLocation.longitude}`;
      const to = `${order.pickup.latitude},${order.pickup.longitude}`;

      this.callMapAPI(from, to, order, tabIndex, orderIndex, '骑手→商家');
    });
  },

  // 计算骑手到用户的距离（待收货）
  calculateRiderToUser(order, tabIndex, orderIndex) {
    this.getCurrentLocation((riderLocation) => {
      if (!riderLocation || !order.delivery.latitude || !order.delivery.longitude) {
        this.updateOrderDistance(tabIndex, orderIndex, '位置获取失败', '位置获取失败');
        return;
      }

      const from = `${riderLocation.latitude},${riderLocation.longitude}`;
      const to = `${order.delivery.latitude},${order.delivery.longitude}`;

      this.callMapAPI(from, to, order, tabIndex, orderIndex, '骑手→用户');
    });
  },

  // 计算商家到用户的距离（待接单）
  calculateMerchantToUser(order, tabIndex, orderIndex) {
    if (!order.pickup.latitude || !order.pickup.longitude ||
        !order.delivery.latitude || !order.delivery.longitude) {
      this.updateOrderDistance(tabIndex, orderIndex, '数据无效', '数据无效');
      return;
    }

    const from = `${order.pickup.latitude},${order.pickup.longitude}`;
    const to = `${order.delivery.latitude},${order.delivery.longitude}`;

    this.callMapAPI(from, to, order, tabIndex, orderIndex, '商家→用户');
  },

  // 调用地图API的通用方法
  callMapAPI(from, to, order, tabIndex, orderIndex, description) {
    const key = app.globalData.locationKey;

    wx.request({
      url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from}&to=${to}&key=${key}`,
      success: (res) => {
        if (res.data.status === 0 && res.data.result.routes.length > 0) {
          const route = res.data.result.routes[0];
          const distance = (route.distance / 1000).toFixed(1); // 转换为公里
          const durationSeconds = route.duration; // API返回的是秒

          // 根据距离合理估算时间
          let estimatedTime;
          const distanceKm = parseFloat(distance);

          if (distanceKm < 5) {
            // 5公里以内，按30km/h计算（城市道路）
            estimatedTime = Math.ceil((distanceKm / 30) * 60); // 分钟
          } else if (distanceKm < 50) {
            // 50公里以内，按50km/h计算（城市+郊区）
            estimatedTime = Math.ceil((distanceKm / 50) * 60); // 分钟
          } else if (distanceKm < 200) {
            // 200公里以内，按80km/h计算（高速）
            estimatedTime = Math.ceil((distanceKm / 80) * 60); // 分钟
          } else {
            // 超过200公里，按100km/h计算，转换为小时显示
            const hours = (distanceKm / 100).toFixed(1);
            estimatedTime = `${hours}小时`;
          }

          const timeDisplay = typeof estimatedTime === 'number' ? `${estimatedTime}分钟` : estimatedTime;

          this.updateOrderDistance(tabIndex, orderIndex, `${distance}km`, timeDisplay);
        } else {
          this.updateOrderDistance(tabIndex, orderIndex, '计算失败', '计算失败');
        }
      },
      fail: (error) => {
        this.updateOrderDistance(tabIndex, orderIndex, '网络错误', '网络错误');
      }
    });
  },

  // 更新订单距离和时间的辅助方法
  updateOrderDistance(tabIndex, orderIndex, distance, eta) {
    const updateKey = `orders.${tabIndex}[${orderIndex}]`;
    this.setData({
      [`${updateKey}.distance`]: distance,
      [`${updateKey}.eta`]: eta
    });

    // 如果是当前显示的标签，更新订单列表
    if (this.data.currentTab === tabIndex) {
      this.updateOrderList(tabIndex);
    }
  },

  goToMap(e) {
    const index = e.currentTarget.dataset.index;
    const order = this.data.orderList[index];

    const pickup = encodeURIComponent(JSON.stringify(order.pickup));
    const delivery = encodeURIComponent(JSON.stringify(order.delivery));
    const statusText = order.statusText;
    const goods = encodeURIComponent(JSON.stringify(order.goodsInfoList || []));
    const orderSn = order.orderSn;
    const userId = order.userId;

    wx.setStorageSync('pickup', pickup);
    wx.setStorageSync('delivery', delivery);
    wx.setStorageSync('orderStatus', statusText);
    wx.setStorageSync('orderSn', orderSn);
    wx.setStorageSync('userId', userId);
    wx.setStorageSync('goods', goods); // ✅ 缓存商品数据

    // ✅ 用 navigateTo 跳转非 tabBar 页面
    wx.switchTab({
      url: '/pages/order/index',
    });
  }
});
